package com.xique.door.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.door.bean.domain.Notice;
import com.xique.door.bean.domain.Problem;
import com.xique.door.bean.domain.User;
import com.xique.door.bean.domain.UserProblem;
import com.xique.door.mapper.NoticeMapper;
import com.xique.door.mapper.ProblemMapper;
import com.xique.door.mapper.UserMapper;
import com.xique.door.mapper.UserProblemMapper;
import com.xique.door.service.IProblemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ProblemServiceImpl extends ServiceImpl<ProblemMapper, Problem>
        implements IProblemService {

    @Autowired
    private UserProblemMapper userProblemMapper;
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public AjaxResult insertProblem(List<Long> ids, Long parkId, Long userId) {
        User userSearch = new User();
        userSearch.setBaseUserId(SecurityUtils.getBaseUserId());
        userSearch.setParkId(parkId);
        List<User> userList = userMapper.selectUsers(userSearch);
        if (userList != null||userList.size()>0) {
            User users = userList.get(0);
            if (ids.size() > 0) {
                Long noticeid = null;
                for (Long id : ids) {
                    /**修改投票数量*/
                    Problem problem = baseMapper.selectById(id);
                    noticeid = problem.getNoticeId();
                    if (problem != null) {
                        int number = problem.getNumber() + 1;
                        problem.setNumber(number);
                        int rest = baseMapper.updateById(problem);
                        if (rest > 0) {
                            /**添加投票记录*/
                            UserProblem userProblem = new UserProblem();
                            userProblem.setProblemId(problem.getId());
                            userProblem.setUserId(users.getId());
                            userProblem.setCreateTime(new Date());
                            userProblem.setParkId(parkId);
                            userProblemMapper.insert(userProblem);
                        }
                    } else {
                        return AjaxResult.error("id错误");
                    }
                }
                /**修改参与数量*/
                Notice notice = noticeMapper.selectById(noticeid);
                notice.setNumber(notice.getNumber() + 1);
                noticeMapper.updateById(notice);
            }
            return AjaxResult.error("没有选择选项");
        }
        return AjaxResult.success("该用户没有小区的权限");
    }
}
